//! my_rust
//! 
//! test from rust

use std::{fs, env};
use std::error::Error;

pub struct Config {
  pub query: String,
  pub filename: String,
}

impl Config {
  pub fn new(mut args: env::Args) -> Result<Config, &'static str> {
    args.next();

    let query = match args.next() {
      Some(arg) => arg,
      None => return Err("query not found"),
    };

    let filename = match args.next() {
      Some(arg) => arg,
      None => return Err("filename not found"),
    };

    Ok(Config {query, filename})
  }
}

pub fn run(config: Config) -> Result<(), Box<dyn Error>>{
  let content = fs::read_to_string(config.filename)?;
  
  for line in search(&config.query, &content) {
    println!("{}", line)
  }
  Ok(())
}

/// search string from contents
/// 
/// # Examples
/// ```
/// let str = my_rust::search("123", "123456");
/// assert_eq!("123456");
/// ```
pub fn search<'a>(query: &str, contents: &'a str) -> Vec<&'a str> {
  contents.lines().filter(|line| line.contains(query)).collect()
}

#[cfg(test)]
mod tests {
  use super::*;

  #[test]
  fn on_result() {
    let query = "dks";
    let contents = "\
12jfldl
dksdf  sf";
    assert_eq!(vec!["dksdf  sf"], search(query, contents));
  }
}
